package com.zx._03_并发.chapter_02_synchronized;

public class Synchronize {

    private static String str_static = "1";
    private String str = "2";

    //锁的是当前类
    public synchronized static String getStrStatic1() {
        return str_static;
    }

    //锁的是当前类
    public static String getStrStatic2() {
        synchronized (str_static) {
            return str_static;
        }
    }

    //锁的是当前类
    public static String getStrStatic3() {
        synchronized (Synchronize.class) {
            return str_static;
        }
    }

    public static void main(String[] args) {
        Synchronize syn = new Synchronize();
        new Thread(() -> syn.getStr1()).start();
        new Thread(() -> syn.getStr2()).start();
        new Thread(() -> syn.getStr3()).start();
        new Thread(() -> syn.getStr4()).start();
    }

    //锁的是对象
    public synchronized String getStr1() {
        try {
            System.out.println(1);
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return str;
    }

    //锁的是当前类
    public String getStr2() {
        synchronized (Synchronize.class) {
            try {
                System.out.println(2);
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    //锁的是对象
    public String getStr3() {
        synchronized (this) {
            try {
                System.out.println(3);
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    //锁的是对象
    public String getStr4() {
        synchronized (str) {
            try {
                System.out.println(4);
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

}
